<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type {
  VxeGridListeners,
  VxeGridProps,
  VxeTablePropTypes,
} from '#/adapter/vxe-table';
import type { DefApplicationModel } from '#/api';

import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page } from '@vben/common-ui';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { getValidateRuleByVxe } from '#/api/common/validateByFs';
import {
  DefInterfacePropertyApi,
  DefInterfacePropertyConfig,
} from '#/api/devOperation/ops/defInterfaceProperty';
import { TableAction } from '#/components/table-action';
import { useMessage } from '#/hooks/web/useMessage';

import { gridSchemas, searchFormSchemas } from './data/crud';

const formOptions: VbenFormProps = {
  ...searchFormSchemas,
  collapsed: true,
};

const { createMessage } = useMessage();
const interfaceIdRef = ref<string>('');
const nameRef = ref<string>('');
const editRules = ref<VxeTablePropTypes.EditRules>({});

const gridOptions: VxeGridProps<DefApplicationModel.DefApplicationResultVO> = {
  ...gridSchemas,
  height: 'auto',
  keepSource: true,
  mouseConfig: { selected: true },
  editConfig: { trigger: 'dblclick', mode: 'row', showStatus: true },
  editRules: editRules.value,
  keyboardConfig: {
    isArrow: true,
    isDel: true,
    isEnter: true,
    isTab: true,
    isEdit: true,
    isChecked: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sorts, filters }, formValues) => {
        const queryParams: any = { model: { ...formValues } };
        // 处理排序条件
        const firstSort = sorts[0];
        if (firstSort) {
          queryParams.sort = firstSort.field;
          queryParams.order = firstSort.order;
        }
        queryParams.size = page.pageSize;
        queryParams.current = page.currentPage;
        // 处理筛选条件
        filters.forEach(({ field, values }) => {
          queryParams[field] = values.join(',');
        });
        queryParams.model.interfaceId = interfaceIdRef.value;
        if (!interfaceIdRef.value) {
          createMessage.warning('参数错误，无法查询');
          throw new Error('参数错误，无法查询');
        }

        return DefInterfacePropertyApi.page(queryParams).then((r) => {
          r.total = Number(r.total);
          return r;
        });
      },
      save: ({ body }) => {
        return DefInterfacePropertyApi.batchSave(body);
      },
    },
  },
};

const gridEvents: VxeGridListeners<any> = {
  toolbarButtonClick({ code }) {
    switch (code) {
      case 'myInsert': {
        gridApi.grid?.insert({
          interfaceId: interfaceIdRef.value,
        });
        break;
      }
      default: {
        break;
      }
    }
  },
};

const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents,
  formOptions,
  gridOptions,
});

function reload() {
  gridApi.reload();
}

async function load(tId: string) {
  interfaceIdRef.value = tId || '';

  const rules = await getValidateRuleByVxe(DefInterfacePropertyConfig.Save, {});
  gridApi && rules && (editRules.value = rules);
}

onMounted(async () => {
  const { currentRoute } = useRouter();
  const routeParams = currentRoute.value?.params;
  const routeQuery = currentRoute.value?.query;
  nameRef.value = routeQuery.name as string;
  await load(routeParams.id as string);

  await reload();
});

const handleDelete = async (row: any) => {
  const $grid = gridApi.grid;
  if ($grid) {
    $grid.setPendingRow(row, true);
  }
};
</script>

<template>
  <Page auto-content-height :title="nameRef">
    <Grid :edit-rules="editRules">
      <template #operate="{ row }">
        <TableAction
          :actions="[
            {
              label: '删除',
              type: 'link',
              size: 'small',
              popConfirm: {
                title: '确认要删除吗？',
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
